﻿#include "as_mysql_connpool.h"
#include "as_mysql_connection.h"
#include "as_sleep.h"
#include <mysql.h>

as::db::MysqlConnPool::MysqlConnPool(const MysqlConnConfig& conf, int poolSize)
{
	pool_.reserve(poolSize);
	for (int i = 0; i < poolSize; ++i)
	{
		conn_ = mysql_init(nullptr);
		auto result = mysql_real_connect(conn_, conf.host_.c_str(), conf.user_.c_str(), conf.pw_.c_str(), conf.databases_.c_str(), conf.port_, NULL, 0);
		if (result == nullptr)
		{
			mysql_close(conn_);
			continue;
		}

		pool_.emplace_back(new MysqlConnection(conn_, conf));
	}
}

as::db::MysqlConnPool::~MysqlConnPool()
{
	is_stop_ = true;
	for (auto conn : pool_)
	{
		delete conn;
	}
	pool_.clear();
}

as::db::MysqlConnection* as::db::MysqlConnPool::Pop()
{
	static unsigned char idx = 0;
	auto conn = pool_[idx++];
	if (idx >= pool_.size())
		idx = 0;
	return conn;
}
